package com.xiaoma.common.utils

import android.content.Context
import java.io.BufferedReader
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStreamReader

/**
 * author: liangjingbo
 * date: 2022/11/11
 * describe:
 */
object FileUtils {

    private val TAG = this.javaClass.simpleName + "_XMTag"

    fun getStringFromAssets(context: Context, fileName: String?): String? {
        return try {
            val open = context.assets.open(fileName!!)
            val inputReader = InputStreamReader(open, "UTF-8")
            val bufReader = BufferedReader(inputReader)
            var line: String? = ""
            val builder = StringBuilder()
            while (bufReader.readLine().also { line = it } != null) {
                builder.append(line)
            }
            inputReader.close()
            bufReader.close()
            builder.toString()
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }

    fun saveDataToFile(path: String?, data: ByteArray?) {
        val file = File(path)
        if (file.exists()) {
            file.delete()
        }
        file.createNewFile()
        val fos = FileOutputStream(file)
        fos.write(data)
        fos.flush()
        fos.close()
    }
}